package com.example.wificovv2;

import java.util.List;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.example.database.myDBHelper;
import com.example.wificov.Innitialvaluepic;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.FragmentManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Toast;

public class Innitialvaluemap extends Activity implements LocationListener {
	//Bat dau khoi tao database
	myDBHelper db;
	
    private int mapType = GoogleMap.MAP_TYPE_SATELLITE;
	private LocationManager locationManager;
	static private Location orgLoc;
	private Location currentLoc;
	GoogleMap googleMap;
	UiSettings uisetting;
	LatLng myLatlng;
	int locFlag = 1, pos;	
	MarkerOptions marker = new MarkerOptions();
	int APID;	
	int idAP ;
	String nameAP;
	float xinnitial, yinnitial;
	String mapid, index;
	
	ListView listApIn;
	private EditText apnameinnitial, xposition, yposition, radius, angle;
	private Button btn_plansave, btn_getrealvalue, btn_marker, btn_next;
	MapView map;			
						

			
	
			@Override
			protected void onCreate(Bundle savedInstanceState) {
				super.onCreate(savedInstanceState);
				setContentView(R.layout.activity_innitialvaluepic);
				db = new myDBHelper(Innitialvaluemap.this);
				
				mapid = Innitialvaluemap.this.getIntent().getStringExtra("mapid");
				
				//index = db.getOption(mapid);
				android.app.FragmentManager fragmentManager = getFragmentManager();
		        MapFragment mapFragment =  (MapFragment) fragmentManager.findFragmentById(R.id.pictureMap);
		        orgLoc = currentLoc;
		        googleMap = mapFragment.getMap();
		        // Enable MyLocation Button in the Map
		        googleMap.setMyLocationEnabled(true);
		        googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
		        uisetting = googleMap.getUiSettings();
		        uisetting.setZoomControlsEnabled(false);
		      //Lấy toạ độ của AP cần khảo sát từ database
			  	String[] size = db.getAPpos(idAP);
			  	xinnitial = Float.parseFloat(size[0]);
			  	yinnitial = Float.parseFloat(size[1]);
			  	LatLng ap = new LatLng(xinnitial, yinnitial);
				marker.position(ap);
				marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
				googleMap.addMarker(marker);
				googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(xinnitial, yinnitial), 14));
		       
		        googleMap.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {
					
					@Override
					public void onMyLocationChange(Location arg0) {
						myLatlng = new LatLng(arg0.getLatitude(), arg0.getLongitude());
						if(locFlag == 1)
						{
							googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(myLatlng, 14));
							locFlag = 0;
						}
					}
				});
				
		        listApIn = (ListView) findViewById(R.id.listApInG);
				apnameinnitial = (EditText)findViewById(R.id.apPlan);
				xposition = (EditText)findViewById(R.id.xpos);
				yposition = (EditText)findViewById(R.id.ypos);
				radius = (EditText)findViewById(R.id.radius);
				angle = (EditText)findViewById(R.id.angle);			
				btn_getrealvalue = (Button) findViewById(R.id.getrealvalue);
				btn_plansave = (Button) findViewById(R.id.planmapsave);	
				btn_marker = (Button) findViewById(R.id.makermap);
				btn_next = (Button) findViewById(R.id.nextdetailG);				
				
				
				//Load danh sách các AP thuộc mapId cần khảo sát
				//Khởi tạo dữ liệu cho mảng arr 
			    List<String> name = db.getAPName(Integer.parseInt(mapid));
				final String []  arr = new String[name.size()]; 
			  	ArrayAdapter<String>adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name.toArray(arr));
			  	//Đưa Data source vào ListView
			  	listApIn.setAdapter(adapter);  	
				//Thiết lập sự kiện cho Listview 
			  	listApIn.setOnItemClickListener(new AdapterView.OnItemClickListener() {
					 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
						 pos =  position;
						 // Lấy tên của AP trong vị trí được chọn
						 String item = parent.getAdapter().getItem(position).toString();
						 String[] splitItem = item.split(" ");
						 idAP = Integer.parseInt(splitItem[0]);
						 nameAP = splitItem[1];
						 apnameinnitial.setText(nameAP);
					  }}); 
			  	
			  
			  	
				btn_getrealvalue.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						// luu giu gia tri toa do cua diem duoc chon khao sat
						float xtemp = Float.parseFloat(xposition.getText().toString());
						float ytemp = Float.parseFloat(yposition.getText().toString());
			        	float dist1 = (float) Math.sin((xinnitial*Math.PI / 180.0) * Math.sin(xtemp*Math.PI / 180.0)
	        	                + Math.cos(xinnitial*Math.PI / 180.0) * Math.cos(xtemp*Math.PI / 180.0)
	        	                * Math.cos(yinnitial - ytemp));
			        	dist1 = (float) Math.acos(dist1);
			        	dist1 = (float) (dist1 * 180.0 / Math.PI);
			        	dist1 = (float) (dist1 * 60 * 1.1515);
			        	String L = String.valueOf(dist1);
			        	radius.setText(L);
			        	float dist2 = (float) Math.sin((xtemp*Math.PI / 180.0) * Math.sin(xtemp*Math.PI / 180.0)
	        	                + Math.cos(xtemp*Math.PI / 180.0) * Math.cos(xtemp*Math.PI / 180.0)
	        	                * Math.cos(ytemp - yinnitial));
			        	dist2 = (float) Math.acos(dist1);
			        	dist2 = (float) (dist1 * 180.0 / Math.PI);
			        	dist2 = (float) (dist1 * 60 * 1.1515);
			        	// Tính góc tạo từ điểm đang đo chiếu theo hệ toạ độ với gốc toạ độ là vị trí Access Point
			        	float sinag = (dist2/dist1);
			        	int ang = (int)(Math.asin(sinag));
			        	String A = String.valueOf(ang);
			        	angle.setText(A);
					}
				});
				
				btn_plansave.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {						
						db.addAPPlan(idAP, Float.parseFloat(radius.getText().toString()), Float.parseFloat(angle.getText().toString()),
								Float.parseFloat(xposition.getText().toString()), Float.parseFloat(yposition.getText().toString()));
						xposition.setText("");
						yposition.setText("");
					}
				});
				
							
				btn_marker.setOnClickListener(new View.OnClickListener() {
					public void onClick(View v) {
						float x;
					    float y;
					    x = Integer.parseInt(xposition.getText().toString());
					    y = Integer.parseInt(yposition.getText().toString());
					    
					    // lay du lieu tren 2 textview long and lat danh dau tren map
							
							LatLng latlng = new LatLng(Double.parseDouble(xposition.getText().toString()), 
									Double.parseDouble(yposition.getText().toString()));
							marker.position(latlng);
							marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
							googleMap.addMarker(marker);
					
					}
				});
				
				btn_next.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						// Giu lai trang thai load map ban dau khi chuyen sang activity khac 
						//String name = Innitialvalue.this.getIntent().getStringExtra("mapid");
						if( xposition.getText().toString().equals("") || yposition.getText().toString().equals("") )
							Toast.makeText( Innitialvaluemap.this, "Nhap day du toa do cua AP", Toast.LENGTH_SHORT).show();
						else{
							Intent intent = new Intent(Innitialvaluemap.this,SeekAp.class);						
							intent.putExtra("APID", idAP);
							startActivity(intent);}						
					}});
		}
			
			@Override
			protected void onResume() {
		      super.onResume();
		      //locationManager.requestLocationUpdates(provider, 400, 1, this);
		      //locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
//		      locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
		    }

			protected void setContentView(MapFragment mapFragment) {
				super.setContentView(R.id.picpow);
			}
			
		    /* Remove the locationlistener updates when Activity is paused */
		    @Override
		    protected void onPause() {
		      super.onPause();
		      locationManager.removeUpdates((LocationListener) this);
		    }
			
			public void onLocationChanged(Location location) {
				double lat = (double) (location.getLatitude());
				double lng = (double) (location.getLongitude());
			    xposition.setText(String.valueOf(lat));
			    yposition.setText(String.valueOf(lng));		    
			    currentLoc = location;
			    if (orgLoc == null)
			    {
			    	orgLoc = location;
			    }
			    
			}
			    
			
			@Override
			public void onProviderDisabled(String arg0) {
						
			}

			@Override
			public void onProviderEnabled(String arg0) {
					
			}

			@Override
			public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
						
			} 
			

			@Override
			public boolean onCreateOptionsMenu(Menu menu) {
				return true;
			}
			// chon menu de thay doi cach thuc the hien ban do
			@Override
		    public boolean onOptionsItemSelected(MenuItem item) {
		        super.onOptionsItemSelected(item);

		        switch(item.getItemId()){
		            case R.id.normal_map:
		                mapType = GoogleMap.MAP_TYPE_NORMAL;
		                break;

		            case R.id.satellite_map:
		                mapType = GoogleMap.MAP_TYPE_SATELLITE;
		                break;

		            case R.id.terrain_map:
		                mapType = GoogleMap.MAP_TYPE_TERRAIN;
		                break;

		            case R.id.hybrid_map:
		                mapType = GoogleMap.MAP_TYPE_HYBRID;
		                break;
		        }

		     //   googleMap.setMapType(mapType);
		        return true;
		    }
			
		   

}
